package org.chen.web.handle;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.chen.common.RespUtils;
import org.chen.model.Roles;
import org.chen.model.User;
import org.chen.respmsg.RespEnum;
import org.chen.vo.RespBean;
import org.chen.vo.UserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class CustomAuthenticationSuccessHandler  implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        User user = (User) authentication.getPrincipal();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        for (Roles role : user.getRoles()) {
            if (role.getName().equals("admin")){
                userInfo.setAdmin(true);
            }
        }
        RespBean<UserInfo> result = RespUtils.result(userInfo, RespEnum.LOGIN_SUCCESS);
        PrintWriter writer = response.getWriter();
        String resp = new ObjectMapper().writeValueAsString(result);
        writer.write(resp);
        writer.flush();
        writer.close();
    }
}
